// 管理员面板管理
class AdminPanel {
    constructor() {
        this.currentTab = 'overview';
        this.currentLeaderboard = 'tetris';
        this.bindEvents();
    }

    // 绑定事件
    bindEvents() {
        // 标签页切换
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                const tabName = btn.dataset.tab;
                this.switchTab(tabName);
            });
        });

        // 排行榜游戏切换
        document.querySelectorAll('.leaderboard-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                const gameName = btn.dataset.game;
                this.switchLeaderboard(gameName);
            });
        });

        // 用户搜索
        document.getElementById('user-search')?.addEventListener('input', (e) => {
            this.filterUsers(e.target.value);
        });

        // 用户筛选
        document.getElementById('user-filter')?.addEventListener('change', (e) => {
            this.filterUsersByType(e.target.value);
        });
    }

    // 切换标签页
    switchTab(tabName) {
        // 更新按钮状态
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');

        // 更新内容区域
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.remove('active');
        });
        document.getElementById(`${tabName}-tab`).classList.add('active');

        this.currentTab = tabName;

        // 加载对应数据
        this.loadTabData(tabName);
    }

    // 加载标签页数据
    async loadTabData(tabName) {
        switch (tabName) {
            case 'overview':
                await this.loadOverview();
                break;
            case 'users':
                await this.loadUsers();
                break;
            case 'games':
                await this.loadGameStats();
                break;
            case 'leaderboards':
                await this.loadLeaderboards();
                break;
            case 'analytics':
                await this.loadAnalytics();
                break;
        }
    }

    // 切换排行榜
    switchLeaderboard(gameName) {
        document.querySelectorAll('.leaderboard-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        document.querySelector(`[data-game="${gameName}"]`).classList.add('active');
        
        this.currentLeaderboard = gameName;
        this.loadSpecificLeaderboard(gameName);
    }

    // 加载用户列表
    async loadUsers() {
        try {
            const users = await api.get('/api/admin/users');
            this.renderUsersTable(users);
        } catch (error) {
            showMessage('加载用户列表失败: ' + error.message, 'error');
        }
    }

    // 渲染用户表格
    renderUsersTable(users) {
        const tbody = document.querySelector('#users-table tbody');
        tbody.innerHTML = '';

        users.forEach(user => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${user.username}</td>
                <td>
                    <span class="role-badge ${user.role === 'admin' ? 'admin' : ''}">${user.role}</span>
                </td>
                <td>${new Date(user.createdAt).toLocaleDateString('zh-CN')}</td>
                <td>${user.lastLogin ? new Date(user.lastLogin).toLocaleDateString('zh-CN') : '从未登录'}</td>
                <td>${user.totalGames || 0}</td>
                <td>
                    <span class="${user.isActive ? 'status-active' : 'status-inactive'}">
                        ${user.isActive ? '活跃' : '禁用'}
                    </span>
                </td>
                <td>
                    ${user.username !== 'admin' ? `
                        <button class="action-btn toggle-btn" onclick="adminPanel.toggleUser('${user.username}')">
                            ${user.isActive ? '禁用' : '启用'}
                        </button>
                        <button class="action-btn delete-btn" onclick="adminPanel.deleteUser('${user.username}')">
                            删除
                        </button>
                    ` : '<span style="color: #999;">系统管理员</span>'}
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    // 切换用户状态
    async toggleUser(username) {
        try {
            // 先获取用户信息
            const users = await api.get('/api/admin/users');
            const user = users.find(u => u.username === username);
            
            if (!confirm(`确定要${user?.isActive ? '禁用' : '启用'}用户 ${username} 吗？`)) {
                return;
            }

            const result = await api.put(`/api/admin/users/${username}/toggle`);
            showMessage(result.message, 'success');
            this.loadUsers(); // 重新加载用户列表
        } catch (error) {
            showMessage('操作失败: ' + error.message, 'error');
        }
    }

    // 删除用户
    async deleteUser(username) {
        if (!confirm(`确定要删除用户 ${username} 吗？此操作不可恢复！`)) {
            return;
        }

        try {
            const result = await api.delete(`/api/admin/users/${username}`);
            showMessage(result.message, 'success');
            this.loadUsers(); // 重新加载用户列表
        } catch (error) {
            showMessage('删除失败: ' + error.message, 'error');
        }
    }

    // 加载统计数据
    async loadStats() {
        try {
            const stats = await api.get('/api/admin/stats');
            this.renderStats(stats);
        } catch (error) {
            showMessage('加载统计数据失败: ' + error.message, 'error');
        }
    }

    // 渲染统计数据
    renderStats(stats) {
        // 更新统计卡片
        document.getElementById('total-users').textContent = stats.totalUsers;
        document.getElementById('active-users').textContent = stats.activeUsers;
        document.getElementById('game-sessions').textContent = stats.totalGameSessions;

        // 渲染俄罗斯方块排行榜
        const tbody = document.querySelector('#leaderboard-table tbody');
        tbody.innerHTML = '';

        if (stats.tetrisLeaderboard && stats.tetrisLeaderboard.length > 0) {
            stats.tetrisLeaderboard.forEach((player, index) => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${index + 1}</td>
                    <td>${player.username}</td>
                    <td>${player.highScore}</td>
                    <td>${player.level}</td>
                    <td>${player.lines}</td>
                `;
                tbody.appendChild(row);
            });
        } else {
            const row = document.createElement('tr');
            row.innerHTML = '<td colspan="5" style="text-align: center; color: #999;">暂无俄罗斯方块记录</td>';
            tbody.appendChild(row);
        }

        // 添加其他游戏统计信息
        this.renderGameStats(stats);
    }

    // 渲染游戏统计信息
    renderGameStats(stats) {
        // 在排行榜后添加其他游戏统计
        const leaderboard = document.querySelector('.leaderboard');
        
        // 移除之前的游戏统计
        const existingStats = leaderboard.querySelector('.other-games-stats');
        if (existingStats) {
            existingStats.remove();
        }

        const otherGamesDiv = document.createElement('div');
        otherGamesDiv.className = 'other-games-stats';
        otherGamesDiv.innerHTML = `
            <h4 style="margin-top: 30px;">其他游戏统计</h4>
            <div class="stats-grid">
                <div class="stat-card">
                    <h4>消消乐最高分</h4>
                    <div class="stat-value">${stats.match3HighScore || 0}</div>
                </div>
                <div class="stat-card">
                    <h4>扫雷最佳时间</h4>
                    <div class="stat-value">${stats.minesweeperBestTime || '--'}</div>
                </div>
            </div>
        `;
        
        leaderboard.appendChild(otherGamesDiv);
    }

    // 加载总览数据
    async loadOverview() {
        try {
            const stats = await api.get('/api/admin/overview');
            this.renderOverview(stats);
        } catch (error) {
            showMessage('加载总览数据失败: ' + error.message, 'error');
        }
    }

    // 渲染总览数据
    renderOverview(stats) {
        document.getElementById('overview-total-users').textContent = stats.totalUsers || 0;
        document.getElementById('overview-active-users').textContent = stats.activeUsers || 0;
        document.getElementById('overview-new-users').textContent = stats.newUsersToday || 0;
        document.getElementById('overview-game-sessions').textContent = stats.totalGameSessions || 0;
        document.getElementById('overview-popular-game').textContent = stats.popularGame || '俄罗斯方块';
        document.getElementById('overview-today-games').textContent = stats.todayGames || 0;
        document.getElementById('overview-avg-time').textContent = stats.avgGameTime || '5分钟';
        document.getElementById('overview-online-users').textContent = stats.onlineUsers || 1;

        // 今日最佳成绩
        document.getElementById('today-best-tetris').textContent = 
            stats.todayBest?.tetris || '暂无记录';
        document.getElementById('today-best-snake').textContent = 
            stats.todayBest?.snake || '暂无记录';
        document.getElementById('today-best-flappy').textContent = 
            stats.todayBest?.flappy || '暂无记录';
    }

    // 加载游戏统计数据
    async loadGameStats() {
        try {
            const stats = await api.get('/api/admin/game-stats');
            this.renderGameStats(stats);
        } catch (error) {
            showMessage('加载游戏统计失败: ' + error.message, 'error');
        }
    }

    // 渲染游戏统计数据
    renderGameStats(stats) {
        // 俄罗斯方块
        if (stats.tetris) {
            document.getElementById('tetris-total-games').textContent = stats.tetris.totalGames || 0;
            document.getElementById('tetris-avg-score').textContent = stats.tetris.avgScore || 0;
            document.getElementById('tetris-max-score').textContent = stats.tetris.maxScore || 0;
            document.getElementById('tetris-active-players').textContent = stats.tetris.activePlayers || 0;
        }

        // 消消乐
        if (stats.match3) {
            document.getElementById('match3-total-games').textContent = stats.match3.totalGames || 0;
            document.getElementById('match3-avg-score').textContent = stats.match3.avgScore || 0;
            document.getElementById('match3-max-score').textContent = stats.match3.maxScore || 0;
            document.getElementById('match3-completion-rate').textContent = 
                (stats.match3.completionRate || 0) + '%';
        }

        // 扫雷
        if (stats.minesweeper) {
            document.getElementById('minesweeper-total-games').textContent = stats.minesweeper.totalGames || 0;
            document.getElementById('minesweeper-win-rate').textContent = 
                (stats.minesweeper.winRate || 0) + '%';
            document.getElementById('minesweeper-best-time').textContent = 
                stats.minesweeper.bestTime || '--';
            document.getElementById('minesweeper-avg-time').textContent = 
                stats.minesweeper.avgTime || '--';
        }

        // 贪吃蛇
        if (stats.snake) {
            document.getElementById('snake-total-games').textContent = stats.snake.totalGames || 0;
            document.getElementById('snake-avg-score').textContent = stats.snake.avgScore || 0;
            document.getElementById('snake-max-score').textContent = stats.snake.maxScore || 0;
            document.getElementById('snake-avg-length').textContent = stats.snake.avgLength || 0;
        }

        // 飞翔小鸟
        if (stats.flappy) {
            document.getElementById('flappy-total-games').textContent = stats.flappy.totalGames || 0;
            document.getElementById('flappy-avg-score').textContent = stats.flappy.avgScore || 0;
            document.getElementById('flappy-max-score').textContent = stats.flappy.maxScore || 0;
            document.getElementById('flappy-pass-rate').textContent = 
                (stats.flappy.passRate || 0) + '%';
        }

        // 记忆翻牌
        if (stats.memory) {
            document.getElementById('memory-total-games').textContent = stats.memory.totalGames || 0;
            document.getElementById('memory-completion-rate').textContent = 
                (stats.memory.completionRate || 0) + '%';
            document.getElementById('memory-best-time').textContent = 
                stats.memory.bestTime || '--';
            document.getElementById('memory-avg-moves').textContent = stats.memory.avgMoves || 0;
        }
    }

    // 加载排行榜数据
    async loadLeaderboards() {
        await this.loadSpecificLeaderboard(this.currentLeaderboard);
    }

    // 加载特定游戏排行榜
    async loadSpecificLeaderboard(gameName) {
        try {
            const leaderboard = await api.get(`/api/admin/leaderboard/${gameName}`);
            this.renderLeaderboard(gameName, leaderboard);
        } catch (error) {
            showMessage('加载排行榜失败: ' + error.message, 'error');
        }
    }

    // 渲染排行榜
    renderLeaderboard(gameName, leaderboard) {
        const tbody = document.querySelector('#dynamic-leaderboard-table tbody');
        const header = document.getElementById('leaderboard-header');
        
        // 更新表头
        const gameHeaders = {
            tetris: ['排名', '用户名', '最高分', '等级', '消除行数'],
            match3: ['排名', '用户名', '最高分', '完成时间', '游戏日期'],
            snake: ['排名', '用户名', '最高分', '蛇长度', '游戏日期'],
            flappy: ['排名', '用户名', '最高分', '通过管道', '游戏日期'],
            minesweeper: ['排名', '用户名', '最佳时间', '难度', '游戏日期'],
            memory: ['排名', '用户名', '最佳时间', '步数', '游戏日期']
        };

        header.innerHTML = gameHeaders[gameName].map(h => `<th>${h}</th>`).join('');
        
        tbody.innerHTML = '';
        
        if (leaderboard && leaderboard.length > 0) {
            leaderboard.forEach((player, index) => {
                const row = document.createElement('tr');
                row.innerHTML = this.getLeaderboardRowHTML(gameName, player, index + 1);
                tbody.appendChild(row);
            });
        } else {
            const row = document.createElement('tr');
            row.innerHTML = `<td colspan="${gameHeaders[gameName].length}" style="text-align: center; color: #999;">暂无${this.getGameDisplayName(gameName)}记录</td>`;
            tbody.appendChild(row);
        }
    }

    // 获取排行榜行HTML
    getLeaderboardRowHTML(gameName, player, rank) {
        const rankBadge = rank <= 3 ? `<span class="rank-badge rank-${rank}">${rank}</span>` : rank;
        
        switch (gameName) {
            case 'tetris':
                return `
                    <td>${rankBadge}</td>
                    <td>${player.username}</td>
                    <td>${player.highScore}</td>
                    <td>${player.level || 1}</td>
                    <td>${player.lines || 0}</td>
                `;
            case 'match3':
                return `
                    <td>${rankBadge}</td>
                    <td>${player.username}</td>
                    <td>${player.highScore}</td>
                    <td>${player.completionTime || '--'}</td>
                    <td>${new Date(player.date).toLocaleDateString('zh-CN')}</td>
                `;
            case 'snake':
                return `
                    <td>${rankBadge}</td>
                    <td>${player.username}</td>
                    <td>${player.highScore}</td>
                    <td>${player.length || 0}</td>
                    <td>${new Date(player.date).toLocaleDateString('zh-CN')}</td>
                `;
            case 'flappy':
                return `
                    <td>${rankBadge}</td>
                    <td>${player.username}</td>
                    <td>${player.highScore}</td>
                    <td>${player.pipes || 0}</td>
                    <td>${new Date(player.date).toLocaleDateString('zh-CN')}</td>
                `;
            case 'minesweeper':
                return `
                    <td>${rankBadge}</td>
                    <td>${player.username}</td>
                    <td>${player.bestTime}s</td>
                    <td>${player.difficulty}</td>
                    <td>${new Date(player.date).toLocaleDateString('zh-CN')}</td>
                `;
            case 'memory':
                return `
                    <td>${rankBadge}</td>
                    <td>${player.username}</td>
                    <td>${player.bestTime}s</td>
                    <td>${player.moves}</td>
                    <td>${new Date(player.date).toLocaleDateString('zh-CN')}</td>
                `;
            default:
                return '';
        }
    }

    // 获取游戏显示名称
    getGameDisplayName(gameName) {
        const names = {
            tetris: '俄罗斯方块',
            match3: '消消乐',
            snake: '贪吃蛇',
            flappy: '飞翔小鸟',
            minesweeper: '扫雷',
            memory: '记忆翻牌'
        };
        return names[gameName] || gameName;
    }

    // 加载数据分析
    async loadAnalytics() {
        try {
            const analytics = await api.get('/api/admin/analytics');
            this.renderAnalytics(analytics);
        } catch (error) {
            showMessage('加载数据分析失败: ' + error.message, 'error');
        }
    }

    // 渲染数据分析
    renderAnalytics(analytics) {
        // 这里可以根据实际数据更新图表
        // 目前使用静态数据作为演示
        console.log('Analytics data:', analytics);
    }

    // 用户搜索
    filterUsers(searchTerm) {
        const rows = document.querySelectorAll('#users-table tbody tr');
        rows.forEach(row => {
            const username = row.cells[0]?.textContent.toLowerCase();
            if (username && username.includes(searchTerm.toLowerCase())) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    }

    // 按类型筛选用户
    filterUsersByType(type) {
        const rows = document.querySelectorAll('#users-table tbody tr');
        rows.forEach(row => {
            const role = row.cells[1]?.textContent.toLowerCase();
            const status = row.cells[5]?.textContent.toLowerCase();
            
            let shouldShow = true;
            
            switch (type) {
                case 'active':
                    shouldShow = status.includes('活跃');
                    break;
                case 'inactive':
                    shouldShow = status.includes('禁用');
                    break;
                case 'admin':
                    shouldShow = role.includes('admin');
                    break;
                case 'all':
                default:
                    shouldShow = true;
                    break;
            }
            
            row.style.display = shouldShow ? '' : 'none';
        });
    }

    // 显示管理员面板
    show() {
        this.switchTab('overview'); // 默认显示总览
    }
}

// 创建管理员面板实例
let adminPanel;